package com.imay.live.view.custom;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.CallSuper;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.imay.live.R;
import com.imay.live.adapter.RoomChatAdapter;
import com.imay.live.adapter.RoomUserAdapter;
import com.imay.live.helper.LevelHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.proto.room.RoomActivityTipsNotify;
import com.imay.live.proto.room.RoomChatNotify;
import com.imay.live.proto.room.RoomGameHostAgreeInviteNotify;
import com.imay.live.proto.room.RoomGameHostRefuseInviteNotify;
import com.imay.live.proto.room.RoomGameInviteNotify;
import com.imay.live.proto.room.RoomHouseNotify;
import com.imay.live.proto.room.RoomKickUserNotify;
import com.imay.live.proto.room.RoomLikeNotify;
import com.imay.live.proto.room.RoomRankUpgradeNotify;
import com.imay.live.proto.room.RoomSendGiftNotify;
import com.imay.live.proto.room.RoomSilenceUserNotify;
import com.imay.live.proto.room.RoomTips;
import com.imay.live.proto.room.RoomUserEnterNotify;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ViewUtil;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import java.util.List;
import java.util.Random;

import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil;
import cn.dreamtobe.kpswitch.util.KeyboardUtil;
import cn.dreamtobe.kpswitch.widget.KPSwitchPanelLinearLayout;

/**
 * Created by jeaman on 2017/3/24.
 * 直播UI
 */

public abstract class RoomBaseView extends RelativeLayout implements View.OnClickListener, KeyboardUtil.OnKeyboardShowingListener, TextView.OnEditorActionListener {
    private final static int[] ENTER_ROOM_STRING_ID = {R.string.live_room_enter_1, R.string.live_room_enter_2, R.string.live_room_enter_3, R.string.live_room_enter_4};

    protected View mTopRootView;  //顶部容器
    protected View mActionRootView;   //底部容器

    private KPSwitchPanelLinearLayout mPanelRoot;
    private EditText mChatEt;
    protected ViewGroup mChatRootView;
    private View mInputRootView;    //聊天输入容器（包含软键盘位置）
    private View mEditRootView;    //输入框容器
    private View mChatImageView;    //聊天按钮
    private ViewGroup mCocosContainer;   //cocos容器;
    protected RecyclerView mUserRecyclerView; //用户列表
    protected RecyclerView mMessageRecyclerView; //聊天消息列表
    protected LinearLayout live_message_show; //聊天消息列表 提示
    protected TextView live_message_tv; //聊天消息列表 提示内容
    private View mSpaceView;    //输入框空白处
    protected View mCloseView;
    protected View mGiftRedPointView;

    private ImageView mAvatarIv;  //主播头像
    private ImageView mLevelIv;
    private TextView mNickTv;
    private TextView mNumberTv;
    private TextView mCharmTv;
    private TextView mUidTv;
    private View mFollowView;
    private TextView mFollowTv;
    private Button mSendBtn;
    private TextView mLiveStatusTv;

    private RoomUserAdapter mUserAdapter;
    private RoomChatAdapter mRoomChatAdapter;

    private UserInfoCard mAnchorUserInfo;

    private int mLoadingDataHashCode = 0;
    private int maxgonemessage;//没查看的新消息
    private final int MAXSHOWMESSAGE = 200;
    private final int MAXMOREMESSAGE = 999;//缩略显示
    private boolean onScroll = false;//是否滑动
    private int lastseepostion = 0;//上次停留的视图位置
    private int lastState = 0;
    private boolean istouch =false;//是否属于触摸
    private boolean isbottom =false;//是否到底
    private OnActionListener mListener;
    private int mMarginBottom;  //cocos设置距离底部的距离
    private boolean mCocosViewIsFront;

    private int mUserListScrollState = RecyclerView.SCROLL_STATE_IDLE;   //用户列表滑动状态

    private boolean mIsTouchDown;   //聊天RecyclerView是否被touch

    public RoomBaseView(Context context) {
        super(context);
        init(context);
    }

    public RoomBaseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public RoomBaseView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public RoomBaseView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    protected abstract int getLayoutId();

    @CallSuper
    protected void init(Context context) {
        inflate(context, getLayoutId(), this);
        mCloseView = findViewById(R.id.live_room_iv_close);
        mChatImageView = findViewById(R.id.live_room_iv_chat);
        mCocosContainer = (ViewGroup) findViewById(R.id.live_room_fl_cocos_container);
        mChatRootView = (ViewGroup) findViewById(R.id.live_room_rl_chat);
        mInputRootView = findViewById(R.id.live_room_ll_input);
        mEditRootView = findViewById(R.id.live_room_ll_edit);
        mUserRecyclerView = (RecyclerView) findViewById(R.id.live_room_rv_user);
        mMessageRecyclerView = (RecyclerView) findViewById(R.id.live_room_rv_message);
        live_message_show = (LinearLayout) findViewById(R.id.live_message_show);
        live_message_tv = (TextView) findViewById(R.id.live_message_tv);

        mSpaceView = findViewById(R.id.live_room_view_space);
        mLiveStatusTv = (TextView) findViewById(R.id.live_room_tv_tips);

        mAvatarIv = (ImageView) findViewById(R.id.live_room_iv_avatar);
        mLevelIv = (ImageView) findViewById(R.id.live_room_iv_level);
        mNickTv = (TextView) findViewById(R.id.live_room_tv_nick);
        mNumberTv = (TextView) findViewById(R.id.live_room_tv_number);
        mCharmTv = (TextView) findViewById(R.id.live_room_tv_charm);
        mUidTv = (TextView) findViewById(R.id.live_room_tv_uid);
        mFollowView = findViewById(R.id.live_room_ll_follow);
        mFollowTv = (TextView) findViewById(R.id.live_room_tv_follow);

        mSendBtn = (Button) findViewById(R.id.live_room_btn_send);
        mChatEt = (EditText) findViewById(R.id.live_room_et_chat);
        mPanelRoot = (KPSwitchPanelLinearLayout) findViewById(R.id.live_room_sp_panel);

        mUserRecyclerView.setHasFixedSize(true);
        mUserRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL));
        mUserRecyclerView.addItemDecoration(new VerticalDividerItemDecoration.Builder(context).color(Color.TRANSPARENT)
                .sizeResId(R.dimen.divider_size_user)
                .showLastDivider()
                .build());

        mUserAdapter = new RoomUserAdapter(null);
        mUserRecyclerView.setAdapter(mUserAdapter);

        mMessageRecyclerView.setHasFixedSize(true);
        mMessageRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(context));
        mMessageRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context).color(Color.TRANSPARENT)
                .sizeResId(R.dimen.divider_size_chat)
                .showLastDivider()
                .build());
        mRoomChatAdapter = new RoomChatAdapter(null);
        mMessageRecyclerView.setAdapter(mRoomChatAdapter);
        mMessageRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                onScroll = true;
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    lastState = RecyclerView.SCROLL_STATE_DRAGGING;
                    istouch = true;
                }
                if (layoutManager instanceof LinearLayoutManager && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (lastState == RecyclerView.SCROLL_STATE_DRAGGING) {

                        LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                        int firstlastPosition = linearManager.findLastVisibleItemPosition();
                        int firstVisibleItemPosition = linearManager.findFirstVisibleItemPosition();
                        if (lastseepostion == 0) {
                            lastseepostion = recyclerView.getAdapter().getItemCount() - 1;
                        }
                        if (lastseepostion < firstlastPosition) {
                            lastseepostion = firstlastPosition;
                        }
                        isbottom = firstlastPosition >= mRoomChatAdapter.getItemCount() - 1;
                        if (firstVisibleItemPosition > 0 && lastseepostion < firstlastPosition) {
                            int novisible = recyclerView.getAdapter().getItemCount() - 1 - lastseepostion;
                            if (novisible > 0) {
                                maxgonemessage = novisible;
                                live_message_tv.setText(getResources().getString(R.string.str_live_message_text, maxgonemessage));
                                if (maxgonemessage > MAXMOREMESSAGE) {
                                    maxgonemessage = MAXMOREMESSAGE;
                                    live_message_tv.setText(getResources().getString(R.string.str_live_message_textmore, maxgonemessage));
                                } else {
                                    live_message_tv.setText(getResources().getString(R.string.str_live_message_text, maxgonemessage));
                                }
                                if (live_message_show.getVisibility() != VISIBLE && mMessageRecyclerView.getVisibility() == VISIBLE) {
                                    recyclerView.setPadding(0, 0, 0, live_message_show.getHeight());
                                    ViewUtil.startVisibilityAnimation(live_message_show, VISIBLE);
                                    recyclerView.smoothScrollToPosition(firstlastPosition);
                                }
                            }else {
                                istouch = false;
                            }
                        }else {
                            if (isbottom){
                                maxgonemessage = 0;
                                live_message_show.setVisibility(GONE);
                                mMessageRecyclerView.setPadding(0, 0, 0, 0);
                            }
                        }
                    }
                    lastState = newState;
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    onScroll = false;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        initListener();
    }

    public void attachKeyboard(Activity activity) {
        KeyboardUtil.attach(activity, mPanelRoot, this);
        KPSwitchConflictUtil.attach(mPanelRoot, null, mChatEt);
    }

    private void initListener() {
        findViewById(R.id.live_room_ll_charm).setOnClickListener(this);
        findViewById(R.id.live_room_ll_follow).setOnClickListener(this);
        findViewById(R.id.live_room_iv_chat).setOnClickListener(this);
        findViewById(R.id.live_room_btn_send).setOnClickListener(this);
        findViewById(R.id.live_room_rl_avatar).setOnClickListener(this);
        findViewById(R.id.live_room_view_space).setOnClickListener(this);
        findViewById(R.id.live_message_show).setOnClickListener(this);
        if (mCloseView != null) {
            mCloseView.setOnClickListener(this);
        }

        mChatEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Editable editable = mChatEt.getText();
                AtUserSpan[] atUserSpans = editable.getSpans(0, editable.length(), AtUserSpan.class);
                for (int i = atUserSpans.length - 1; i >= 0; i--) {
                    AtUserSpan atUserSpan = atUserSpans[i];
                    int spanStart = editable.getSpanStart(atUserSpan);
                    if (start > spanStart && start < atUserSpan.length) {
                        int spanEnd = editable.getSpanEnd(atUserSpan);
//                        editable.removeSpan(atUserSpan);
                        mChatEt.setText(editable.delete(spanStart, spanEnd));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                mSendBtn.setEnabled(s.length() > 0);
            }
        });

        mChatEt.setOnEditorActionListener(this);

        mUserRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                mListener.onUserClick(mUserAdapter.getItem(position));
            }
        });

        mUserRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mUserListScrollState = newState;
            }
        });

        mUserAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mLoadingDataHashCode = mUserAdapter.getData().hashCode();
                mListener.onLoadMoreUser(mUserAdapter.getPage() + 1);
            }
        }, mUserRecyclerView);

        mMessageRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                UserInfoCard user = mRoomChatAdapter.getUser(position);
                if (user != null) {
                    mListener.onUserClick(user);
                } else {
                    RoomActivityTipsNotify notify = mRoomChatAdapter.getNotify(position);
                    if (notify != null) {
                        mListener.onNotifyJumpClick(notify.jumpContent);
                    }
                }
            }
        });
    }

    //设置主播资料
    public void setAnchorInfo(UserInfoCard userInfo) {
        mAnchorUserInfo = userInfo;
        if (userInfo != null) {
            GlideUtil.loadCircleBorderImage(mAvatarIv, userInfo.imgHead, R.dimen.border_avatar, R.color.line_ff, R.mipmap.pnl_00_head108);
            int levelRes = LevelHelper.getLiveBadgeResId(userInfo.OfficialVip, userInfo.LargeVipStatus, userInfo.LiveLv);
            mLevelIv.setImageResource(levelRes);
            String nick;
            if (!TextUtils.isEmpty(userInfo.nick) && userInfo.nick.length() > 10) { //  如果昵称长度超出10个字符，只显示10个字符
                nick = getResources().getString(R.string.live_room_max_nick, userInfo.nick.substring(0, 10));
            } else {
                nick = userInfo.nick;
            }
            mNickTv.setText(nick);
            mCharmTv.setText(String.valueOf(userInfo.meiliGain));
            mUidTv.setText(getResources().getString(R.string.live_room_roomid, userInfo.roomId));
            if (userInfo.uid== AccountManager.getInstance().getUid()){
                setFollowUser(true);
            }else{
                setFollowUser(userInfo.myFollow);
            }
        }
    }

    public void setUserPageSize(int userPageSize) {
        mUserAdapter.setPageSize(userPageSize);
    }

    //设置用户列表
    public void setUserData(List<UserInfoCard> userList) {
        mLoadingDataHashCode = 0;
        mUserAdapter.setNewData(userList);
    }

    public List<UserInfoCard> getUserData() {
        return mUserAdapter.getData();
    }

    //添加用户(加载更多)
    public void addUserData(List<UserInfoCard> userList) {
        //忽略非上次请求
        if (mLoadingDataHashCode != 0 && mLoadingDataHashCode == mUserAdapter.getData().hashCode()) {
            mUserAdapter.addData(userList);
        }
    }

    //加载更多失败
    public void setUserLoadMoreFailed() {
        //忽略非上次请求
        if (mLoadingDataHashCode != 0 && mLoadingDataHashCode == mUserAdapter.getData().hashCode()) {
            mUserAdapter.setLoadMoreFailed();
        }
    }

    //设置在线人数
    public void setUserNumber(long number) {
        mNumberTv.setText(getResources().getString(R.string.live_room_number, number));
    }

    //自己进入
    public void addEnterRoomMessage(String nick) {
        int id = ENTER_ROOM_STRING_ID[new Random().nextInt(ENTER_ROOM_STRING_ID.length - 1)];
        addMessage(getResources().getString(id, nick));
    }

    //聊天
    public void addChatMessage(RoomChatNotify roomChatNotify) {
        addMessage(roomChatNotify);
    }

    //进入房间
    public void addChatMessage(RoomUserEnterNotify roomUserEnterNotify) {
        addMessage(roomUserEnterNotify);
    }

    //点赞
    public void addChatMessage(RoomLikeNotify roomLikeNotify) {
        if (roomLikeNotify == null || roomLikeNotify.user == null) {
            return;
        }
        addMessage(roomLikeNotify);
    }

    //送礼物
    public void addChatMessage(RoomSendGiftNotify roomSendGiftNotify) {
        if (roomSendGiftNotify == null || roomSendGiftNotify.sender == null) {
            return;
        }
        addMessage(roomSendGiftNotify);
    }

    //房间公告
    public void addChatMessage(RoomTips roomTips) {
        addMessage(roomTips);
    }

    //踢人
    public void addChatMessage(RoomKickUserNotify roomKickUserNotify) {
        if (roomKickUserNotify == null || roomKickUserNotify.actionUser == null || roomKickUserNotify.kickedUser == null) {
            return;
        }
        addMessage(roomKickUserNotify);
    }

    //禁言
    public void addChatMessage(RoomSilenceUserNotify roomSilenceUserNotify) {
        if (roomSilenceUserNotify == null || roomSilenceUserNotify.actionUser == null || roomSilenceUserNotify.kickedUser == null) {
            return;
        }
        addMessage(roomSilenceUserNotify);
    }

    //游戏邀请
    public void addChatMessage(RoomGameInviteNotify roomGameInviteNotify) {
        if (roomGameInviteNotify == null || roomGameInviteNotify.fromuser == null) {
            return;
        }
        addMessage(roomGameInviteNotify);
    }

    //游戏同意
    public void addChatMessage(RoomGameHostAgreeInviteNotify roomGameHostAgreeInviteNotify) {
        if (roomGameHostAgreeInviteNotify == null || roomGameHostAgreeInviteNotify.fromuser == null) {
            return;
        }
        addMessage(roomGameHostAgreeInviteNotify);
    }

    //游戏拒绝
    public void addChatMessage(RoomGameHostRefuseInviteNotify roomGameHostRefuseInviteNotify) {
        addMessage(roomGameHostRefuseInviteNotify);
    }
    //送礼物
    public void addHouseMessage(RoomHouseNotify roomHouseNotify) {
        if (roomHouseNotify == null || roomHouseNotify.sender == null) {
            return;
        }
        addMessage(roomHouseNotify);
    }

    //直播间活动公告通知
    public void addChatMessage(RoomActivityTipsNotify roomActivityTipsNotify) {
        addMessage(roomActivityTipsNotify);
    }

    //榜单提升通知(房间公屏区)
    public void addChatMessage(RoomRankUpgradeNotify roomRankUpgradeNotify) {
        addMessage(roomRankUpgradeNotify);
    }

    private void addMessage(Object message) {
        mRoomChatAdapter.addData(message);
        ShowTipsNum(mRoomChatAdapter, mMessageRecyclerView, live_message_show);
    }

    /**
     * 显示未阅读处理
     *
     * @param adapter
     * @param recyclerView
     * @param showview
     */
    private void ShowTipsNum(BaseQuickAdapter adapter, RecyclerView recyclerView, View showview) {
        try {
            if (!onScroll) {
                maxgonemessage = mRoomChatAdapter.getData().size() - lastseepostion - 1;
                if (maxgonemessage > 0 && !isbottom && istouch) {
                    if (maxgonemessage > MAXMOREMESSAGE) {
                        maxgonemessage = MAXMOREMESSAGE;
                        if (adapter.getItemCount() >= MAXSHOWMESSAGE) {
                            adapter.getData().subList(lastseepostion + 1, lastseepostion + 2).clear();
                        }
                        live_message_tv.setText(getResources().getString(R.string.str_live_message_textmore, maxgonemessage));
                    } else {
                        live_message_tv.setText(getResources().getString(R.string.str_live_message_text, maxgonemessage));
                    }
                    if (live_message_show.getVisibility() != VISIBLE && mMessageRecyclerView.getVisibility() == VISIBLE) {
                        recyclerView.setPadding(0, 0, 0, live_message_show.getHeight());
                        ViewUtil.startVisibilityAnimation(live_message_show, VISIBLE);
//                        recyclerView.scrollToPosition(lastseepostion - 1);
                    }
                }else {
                    maxgonemessage = 0;
                    int toindex = adapter.getData().size() - MAXSHOWMESSAGE;
                    if (toindex > 0) {
                        adapter.getData().subList(0, toindex).clear();
                        adapter.notifyItemRangeRemoved(0,1);
                    }
                    recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                }
            }

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void setFollowUser(boolean follow) {
        mFollowView.setVisibility(follow ? INVISIBLE : VISIBLE);
        mFollowTv.setVisibility(follow ? GONE : VISIBLE);
    }

    public View getChatRecyclerView() {
        return mMessageRecyclerView;
    }

    public boolean isShowInputView() {
        return mPanelRoot.getVisibility() != View.GONE;
    }

    public void setGiftRedPointViewVisible(boolean visible) {
        if (mGiftRedPointView != null) {
            mGiftRedPointView.setVisibility(visible ? VISIBLE : GONE);
        }
    }

    //隐藏输入框，显示其他控件
    @CallSuper
    public void hideInputView() {
        if (isShowInputView()) {
            KPSwitchConflictUtil.hidePanelAndKeyboard(mPanelRoot);
        }
        mEditRootView.setVisibility(GONE);
        mSpaceView.setVisibility(GONE);
        setActionViewVisibility(true);
        updateInputRootViewMargin();
    }

    //显示输入框
    @CallSuper
    protected void showInputView() {
        bringChatToFront(); //如果cocos在最顶层，需要调整输入框到最顶层
        KPSwitchConflictUtil.showKeyboard(mPanelRoot, mChatEt);
        mEditRootView.setVisibility(VISIBLE);
        mSpaceView.setVisibility(VISIBLE);
        setActionViewVisibility(false);
        updateInputRootViewMargin();
    }

    //设置输入框距离底部的高度
    private void updateInputRootViewMargin() {
        int bottom;
        if (isShowInputView()) {
            bottom = 0;    //显示输入框时高度为0
        } else {
            bottom = getResources().getDimensionPixelOffset(R.dimen.room_bottom_margin);
            bottom += mMarginBottom;   //cocos高度
        }
        LayoutParams layoutParams = (LayoutParams) mInputRootView.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, bottom);
        mInputRootView.setLayoutParams(layoutParams);
    }

    public void setOnActionListener(OnActionListener actionListener) {
        this.mListener = actionListener;
    }

    //美颜显示时隐藏部分界面
    public void onShowBeautyView() {

    }

    //美颜关闭后恢复界面
    public void onHideBeautyView() {

    }

    //cocos需要隐藏或者显示底部的view
    public void setBottomViewVisibility(boolean visible) {
        setActionViewVisibility(visible);
        setMessageViewVisibility(visible);
    }

    @CallSuper
    public void setActionViewVisibility(boolean visible) {
        int visibility = visible ? VISIBLE : INVISIBLE;
        ViewUtil.startVisibilityAnimation(mActionRootView, visibility);
    }

    public void setMessageViewVisibility(boolean visible) {
        int visibility = visible ? VISIBLE : INVISIBLE;
        ViewUtil.startVisibilityAnimation(mMessageRecyclerView, visibility);

        if (visible && maxgonemessage > 0 && lastseepostion > 0) {
            if (live_message_show.getVisibility() != VISIBLE) {
                ViewUtil.startVisibilityAnimation(live_message_show, VISIBLE);
            }
        } else {
            live_message_show.setVisibility(INVISIBLE);
        }

    }

    @CallSuper
    public void setTopViewVisibility(boolean visible) {
        int visibility = visible ? VISIBLE : INVISIBLE;
        if (mTopRootView != null) {
            mTopRootView.findViewById(R.id.live_room_ll_user).setVisibility(visibility);
        }
    }

    //重置用户列表和聊天列表
    public void reset() {
        hideLiveStatusTips();
        mRoomChatAdapter.setNewData(null);
        mUserAdapter.setNewData(null);
    }

    //恢复cocos相关设置
    public void resetCocosSetting() {
        bringCocosToBack();
        setBottomMargin(0);
        setBottomViewVisibility(true);
        setTopViewVisibility(true);
        setActionViewVisibility(true);
    }

    public void setAtUser(UserInfoCard userInfoCard) {
        SpannableString atUserSpan = new AtUserSpan().getSpan(userInfoCard.uid, userInfoCard.nick);
        mChatEt.setText(atUserSpan);
        mChatEt.setSelection(atUserSpan.length());
        post(new Runnable() {
            @Override
            public void run() {
                showInputView();
            }
        });
    }

    //用户列表是否正在滑动
    public boolean isUserListScrolling() {
        return mUserListScrollState != RecyclerView.SCROLL_STATE_IDLE;
    }

    @CallSuper
    public boolean onBackPressed() {
        if (isShowInputView()) {
            hideInputView();
            return true;
        }
        return false;
    }

    @CallSuper
    @Override
    public void onClick(View v) {
        //点击空白隐藏软键盘
        if (v == this) {
            hideInputView();
        } else {
            switch (v.getId()) {
                case R.id.live_room_view_space:
                    hideInputView();
                    break;
                case R.id.live_room_ll_charm:
                    mListener.onRankingClick();
                    break;
                case R.id.live_room_iv_chat:    //聊天
                    showInputView();
                    break;
                case R.id.live_room_iv_close:
                    mListener.onCloseClick();
                    break;
                case R.id.live_room_ll_follow:  //关注
                    if (mAnchorUserInfo != null) {
                        mListener.onFollowClick(mAnchorUserInfo.uid);
                    }
                    break;
                case R.id.live_room_btn_send:
                    sendMessage();
                    break;
                case R.id.live_room_rl_avatar:
                    if (mAnchorUserInfo != null) {
                        mListener.onUserClick(mAnchorUserInfo);
                    }
                    break;
                case R.id.live_message_show:
                    maxgonemessage = 0;
                    istouch = false;
                    if (mRoomChatAdapter.getItemCount() >= MAXSHOWMESSAGE) {
                        mRoomChatAdapter.getData().subList(0, mRoomChatAdapter.getItemCount() - MAXSHOWMESSAGE).clear();
                    }
                    lastseepostion = mRoomChatAdapter.getItemCount()-1;
                    onScroll = false;
                    hideInputView();
                    ViewUtil.startVisibilityAnimation(live_message_show, GONE);
                    mMessageRecyclerView.setPadding(0, 0, 0, 0);
                    try {
                        mMessageRecyclerView.scrollToPosition(mRoomChatAdapter.getItemCount() - 1);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    private void sendMessage() {
        Editable editable = mChatEt.getText();

        long uid = 0;
        String message = editable.toString();
        AtUserSpan[] atUserSpans = editable.getSpans(0, editable.length(), AtUserSpan.class);
        if (atUserSpans.length > 0) {   //只处理一个span
            AtUserSpan atUserSpan = atUserSpans[0];
            int spanStart = editable.getSpanStart(atUserSpan);
            int spanEnd = editable.getSpanEnd(atUserSpan);
            message = editable.delete(spanStart, spanEnd).toString();
            uid = atUserSpan.uid;
        }
        mListener.onSendClick(uid, message);
        mChatEt.setText(null);
    }

    @CallSuper
    @Override
    public void onKeyboardShowing(boolean isShowing) {
        //关闭键盘
        if (!isShowing && isShowInputView()) {
            bringChatToMiddle();    //关闭输入框时，如果cocos之前被设置在最顶层，恢复cocos在最顶层
            post(new Runnable() {
                @Override
                public void run() {
                    hideInputView();
                }
            });
        }
        mListener.onKeyboardShowing(isShowing, mPanelRoot.getMeasuredWidth(), mPanelRoot.getMeasuredHeight() == 0 ? KeyboardUtil.getKeyboardHeight(getContext()) : mPanelRoot.getMeasuredHeight());
    }

    @CallSuper
    public void setStatusBarHeight(int top) {
        if (mTopRootView != null) {
            LayoutParams layoutParams = (LayoutParams) mTopRootView.getLayoutParams();
            layoutParams.setMargins(layoutParams.leftMargin, top, layoutParams.rightMargin, layoutParams.bottomMargin);
            mTopRootView.setLayoutParams(layoutParams);
        }
        if (mCloseView != null) {
            LayoutParams layoutParams = (LayoutParams) mCloseView.getLayoutParams();
            layoutParams.setMargins(layoutParams.leftMargin, top, layoutParams.rightMargin, layoutParams.bottomMargin);
            mCloseView.setLayoutParams(layoutParams);
        }
    }

    @CallSuper
    public void setBottomMargin(int bottom) {
        mMarginBottom = bottom;
        if (mActionRootView != null) {
            mActionRootView.setPadding(mActionRootView.getPaddingLeft(), mActionRootView.getPaddingTop(), mActionRootView.getPaddingRight(), bottom);
        }
        updateInputRootViewMargin();
    }

    public ViewGroup getCocosContainer() {
        return mCocosContainer;
    }

    //设置cocos在最顶层
    public void bringCocosToFront() {
        mCocosViewIsFront = true;
        if (mChatRootView != null) {
            mCocosContainer.bringToFront();
        }
    }

    //设置cocos在最底层
    public void bringCocosToBack() {
        mCocosViewIsFront = false;
        if (mTopRootView != null) {
            mTopRootView.bringToFront();
        }
        if (mChatRootView != null) {
            mChatRootView.bringToFront();
        }
    }

    //如果cocos在最顶层，如果将输入框调整到最顶层
    private void bringChatToFront() {
        if (mCocosViewIsFront) {
            mChatRootView.bringToFront();
        }
    }

    //关闭输入框时，恢复cocos层在最顶层
    private void bringChatToMiddle() {
        if (mCocosViewIsFront) {
            mCocosContainer.bringToFront();
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == v.getImeActionId() && v == mChatEt) {
            if (!TextUtils.isEmpty(mChatEt.getText().toString().trim())) {
                sendMessage();
            }
        }
        return false;
    }

    public void showLiveStatusTips(String tips) {
        mLiveStatusTv.setText(tips);
        mLiveStatusTv.setVisibility(VISIBLE);
    }

    public void hideLiveStatusTips() {
        mLiveStatusTv.setVisibility(GONE);
    }

    public void updateCharm(long charm) {
        mCharmTv.setText(String.valueOf(charm));
    }

    //播放子类按需实现该方法
    public boolean isHideAllView() {
        return false;
    }

    //播放子类按需实现该方法
    public boolean toggleSimpleMode(boolean simple) {
        return false;
    }

    public interface OnActionListener {
        void onRankingClick();
        void onCloseClick();
        void onSendClick(long uid, String content);
        void onUserClick(UserInfoCard userInfo);
        void onNotifyJumpClick(String command);
        void onFollowClick(long uid);
        void onLoadMoreUser(int page);
        void onKeyboardShowing(boolean isShowing, int width, int height);
    }

    public class AtUserSpan extends ForegroundColorSpan {
        private long uid;
        private int length;
        public AtUserSpan() {
            super(getResources().getColor(R.color.text_chat_at));
        }

        public SpannableString getSpan(long uid, String nick) {
            this.uid = uid;
            String at = getContext().getString(R.string.live_room_chat_at, nick);
            this.length = at.length();
            SpannableString span = new SpannableString(at);
            span.setSpan(this, 0, at.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return span;
        }
    }

    public boolean isInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mIsTouchDown = mMessageRecyclerView != null && ev.getX() >= mMessageRecyclerView.getLeft() && ev.getX() <= mMessageRecyclerView.getRight() && ev.getY() >= mMessageRecyclerView.getTop() && ev.getY() <= mMessageRecyclerView.getBottom();
                break;
            case MotionEvent.ACTION_UP:
                mIsTouchDown = false;
                break;
        }
        return mIsTouchDown;
    }

}
